package com.heima.comment.service.impl;

import com.heima.aliyun.GreenTextScan;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.UserFeign;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vo.ApCommentRepayVO;
import com.heima.model.comment.vo.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.wemedia.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @package com.heima.comment.service.impl
 * @Date 2022/3/10
 * @project heima-leadnews
 */
@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private ArticleFeign articleFeign;

    /**
     * 加载回复评论列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
        //参数校验
        if (dto.getSize() == null || dto.getSize() == 0) {
            dto.setSize(10);
        }
        //根据条件查询评论列表
        PageRequest page = PageRequest.of(0, dto.getSize());
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime").lt(dto.getMinDate()));
        query.with(page);
        Sort sort = Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);
        List<ApCommentRepay> apComments = mongoTemplate.find(query, ApCommentRepay.class);
        ;
        //判断当前用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            //如果未登录直接返回评论列表
            return ResponseResult.okResult(apComments);
        }
        ArrayList<ApCommentRepayVO> list = new ArrayList<>();
        //遍历评论列表
        for (ApCommentRepay apCommentRepay : apComments) {
            ApCommentRepayVO apCommentRepayVO = new ApCommentRepayVO();
            BeanUtils.copyProperties(apCommentRepay, apCommentRepayVO);
            //如果登录了 需要检查在当前回复评论列表中 哪些评论登陆人点赞过
            Query queryLike = Query.query(Criteria.where("commentRepayId").is(apCommentRepay.getId()).and("authorId").is(user.getId()));
            //根据当前列表中评论id  和  登录人id 查询评论点赞表，得到点赞数据
            ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(queryLike, ApCommentRepayLike.class);

            if (apCommentRepayLike != null) {
                apCommentRepayVO.setOperation((short) 0);
            }
            list.add(apCommentRepayVO);

        }


        return ResponseResult.okResult(list);
    }

    /**
     * 保存回复评论点赞
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        try {
            Map map = greenTextScan.greenTextScan(dto.getContent());
            ApCommentRepay apCommentRepay = new ApCommentRepay();

            String suggestion = (String) map.get("suggestion");
            switch (suggestion) {
                case "pass":
                    apCommentRepay.setContent(dto.getContent());
                    break;
                case "block":
                    apCommentRepay.setContent((String) map.get("filteredContent"));
                    break;
                case "review":
                    apCommentRepay.setContent(dto.getContent());
                    break;
                default:
                    break;
            }
            ResponseResult<ApUser> userRssult = userFeign.findUserById(user.getId());
            ApUser userLogin = userRssult.getData();
            apCommentRepay.setAuthorId(userLogin.getId());
            apCommentRepay.setAuthorName(userLogin.getName());
            apCommentRepay.setCreatedTime(new Date());
            apCommentRepay.setUpdatedTime(new Date());
            apCommentRepay.setCommentId(dto.getCommentId());
            apCommentRepay.setLikes(0);
            mongoTemplate.save(apCommentRepay);
            Query query = Query.query(Criteria.where("id").is(dto.getCommentId()));
            ApComment apComment = mongoTemplate.findOne(query, ApComment.class);
            Update update = new Update();
            update.set("reply",apComment.getReply()+1);
            mongoTemplate.updateMulti(query,update,ApComment.class);
            log.info("保存成功 {}", apCommentRepay.getContent());
        } catch (Exception e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "远程审核回复评论出错");
        }

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {
        //判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //根据回复id查询评论数据
        Query query = Query.query(Criteria.where("commentRepayId").is(dto.getCommentRepayId()).and("authorId").is(user.getId()));
        ApCommentRepayLike like = mongoTemplate.findOne(query, ApCommentRepayLike.class);
        Query queryRepay = Query.query(Criteria.where("id").is(dto.getCommentRepayId()));
        ApCommentRepay apCommentRepay = mongoTemplate.findOne(queryRepay, ApCommentRepay.class);
        HashMap<String, Integer> map = new HashMap<>();
        if (dto.getOperation() == 0) {
            if (like != null) {
                CustException.cust(AppHttpCodeEnum.DATA_EXIST, "不要重复评论回复点赞");
            }
            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setAuthorId(user.getId());
            apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());
            apCommentRepayLike.setOperation((short) 0);
            mongoTemplate.save(apCommentRepayLike);
            Update update = new Update();
            update.set("likes", apCommentRepay.getLikes() + 1);
            mongoTemplate.updateMulti(queryRepay, update, ApCommentRepay.class);
            map.put("likes", apCommentRepay.getLikes() + 1);

        } else {
            if (apCommentRepay.getLikes() - 1 < 0) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW);
            }
            mongoTemplate.remove(query,ApCommentRepayLike.class);
            Update update = new Update();
            update.set("likes", apCommentRepay.getLikes() - 1);
            mongoTemplate.updateMulti(queryRepay, update, ApCommentRepay.class);
            map.put("likes", apCommentRepay.getLikes() - 1);
        }
        return ResponseResult.okResult(map);
    }
}
